package com.media.revision.adapter;

import android.app.Activity;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.baselibrary.utils.GlideUtils;
import com.baselibrary.utils.ToastUtils;
import com.media.AlbumManageUtils;
import com.media.R;
import com.media.image.ImageModel;
import com.media.image.ViewPagerCacheBean;
import com.media.revision.RevisionMediaActivity;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import co.senab.photoview.PhotoView;

/**
 * 浏览
 */
public class PreviewPageAdapter extends PagerAdapter {
    private Activity mActivity;
    private List<ImageModel> datas = new ArrayList<>();
    private ArrayList<ImageModel> mPreviewSelectImageList = new ArrayList<>();//
    private OnCloseClickListener mOnCloseClickListener;
    private OnSelectTypeClickListener mOnSelectTypeClickListener;
    private OnSelectClickListener onSelectClickListener;
    public OnKeyDownClickListener mOnKeyDownClickListener;
    private int count, selectMax, finalNumber, mSlidePro;
    private String selectType = "";
    private String indexOf = "";//从相册列表点击被选中的item
    private LinkedHashMap<Integer, ViewPagerCacheBean> mViewPagerCacheMap = new LinkedHashMap<>();
    public LinkedHashMap<String, VideoView> mFirstVideoViewMap = new LinkedHashMap<>();
    public LinkedHashMap<String, ImageView> mFirstIvControlViewMap = new LinkedHashMap<>();//首次点开视频才会使用

    public PreviewPageAdapter(Activity mActivity, ProgressBar progressBar) {
        this.mActivity = mActivity;
    }


    public void setViewPagerCacheMap(LinkedHashMap<Integer, ViewPagerCacheBean> mViewPagerCacheMap) {
        this.mViewPagerCacheMap = mViewPagerCacheMap;
    }

    public void setData(List<ImageModel> list) {
        this.datas = list;
        notifyDataSetChanged();
    }

    public void upDataBean(ImageModel imageModel) {
        int pos = datas.indexOf(imageModel);
        if (pos != -1) {
            datas.remove(pos);//删除旧数据
            datas.set(pos, imageModel);//添加到之前指定位置
            notifyDataSetChanged();
        }
    }

    public void setCount(int count, int selectMax, int finalNumber) {
        this.count = count;
        this.selectMax = selectMax;
        this.finalNumber = finalNumber;
    }

    public void setSelectType(String selectType) {
        this.selectType = selectType;
    }

    public void setOnIndexOf(String indexOf) {
        this.indexOf = indexOf;
    }

    public void setSelectImageList(ArrayList<ImageModel> selectImageList) {
        this.mPreviewSelectImageList = selectImageList;
    }

    public void setFirstVideoViewMap(LinkedHashMap<String, VideoView> mFirstVideoViewMap) {
        this.mFirstVideoViewMap = mFirstVideoViewMap;
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        View view = LayoutInflater.from(container.getContext()).inflate(R.layout.revision_media_view_page_gallery_item, container, false);
        final PhotoView photoView = view.findViewById(R.id.img);
        LinearLayout mLlPreviewClose = view.findViewById(R.id.ll_preview_close);
        final TextView mTvSelectType = view.findViewById(R.id.tv_select_type);
        final LinearLayout mLl_select_type = view.findViewById(R.id.ll_select_type);
        LinearLayout mLlPreviewSelect = view.findViewById(R.id.ll_preview_select);
        final ImageView mIvPreviewSelect = view.findViewById(R.id.iv_preview_select);
        final TextView mTvPreviewSelect = view.findViewById(R.id.tv_preview_select);
        RelativeLayout mRlVideo = view.findViewById(R.id.rl_video);
        final VideoView mVvPreviewVideo = view.findViewById(R.id.vv_preview_video);
        TextView mTvCurrentSpeed = view.findViewById(R.id.tv_current_speed);
        TextView mTvTotalSpeed = view.findViewById(R.id.tv_total_speed);
        SeekBar mSbSpeed = view.findViewById(R.id.sb_speed);
        final ImageView mIvVideoControl = view.findViewById(R.id.iv_preview_video);
        final ImageModel imageModel = datas.get(position);
        ViewPagerCacheBean mPagerCacheBean = new ViewPagerCacheBean();
        if (imageModel.getType().equals(ImageModel.TYPE_IMAGE)) {
            mRlVideo.setVisibility(View.GONE);
            GlideUtils.loadImg_228(mActivity.getApplicationContext(), imageModel.getPath(), photoView);
        } else if (imageModel.getType().equals(ImageModel.TYPE_VIDEO)) {
            mRlVideo.setVisibility(View.VISIBLE);
            photoView.setVisibility(View.GONE);
            mVvPreviewVideo.setVideoPath(imageModel.getPath());//设置视频文件
            if (mViewPagerCacheMap.size() == 0 || indexOf.equals(String.valueOf(position))) {
                mVvPreviewVideo.start();
                mFirstVideoViewMap.put("firstVideo", mVvPreviewVideo);
                mFirstIvControlViewMap.put("firstControlVideo", mIvVideoControl);
                mIvVideoControl.setSelected(true);
            } else {
                mIvVideoControl.setSelected(false);
            }
            mPagerCacheBean.setVideoView(mVvPreviewVideo);
            mPagerCacheBean.setIvVideoPlayState(mIvVideoControl);
            setVideoListener(mVvPreviewVideo, mIvVideoControl, mTvCurrentSpeed, mTvTotalSpeed, mSbSpeed);
        }
        mPagerCacheBean.setTvSelectType(mTvSelectType);
        mPagerCacheBean.setLlSelectType(mLl_select_type);
        mPagerCacheBean.setLlPreView(mLlPreviewSelect);
        mPagerCacheBean.setIvPreviewSelect(mIvPreviewSelect);
        mPagerCacheBean.setTvPreviewSelect(mTvPreviewSelect);
        mPagerCacheBean.setImageModel(imageModel);
        mViewPagerCacheMap.put(position, mPagerCacheBean);
        // setSelectTypeClick(mTvSelectType, mLl_select_type, mLlPreviewSelect, imageModel);
        mIvPreviewSelect.setVisibility(imageModel.getIsChecked() ? View.GONE : View.VISIBLE);
        mTvPreviewSelect.setVisibility(imageModel.getIsChecked() ? View.VISIBLE : View.GONE);
        mTvPreviewSelect.setText(String.valueOf(imageModel.getSelsctRanking()));
        //这里的onBack事件，每次都会创建新的对象，所有在外层通过 mCurrentPage 字段进行关闭视频
        mOnKeyDownClickListener = new OnKeyDownClickListener() {
            @Override
            public void onKeyDownClick() {
                mVvPreviewVideo.pause();
                if (mOnCloseClickListener != null)
                    mOnCloseClickListener.onCloseClick(mPreviewSelectImageList, position, selectType);
            }
        };
        mIvVideoControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVvPreviewVideo.isPlaying()) {
                    mVvPreviewVideo.pause();
                    mIvVideoControl.setSelected(false);
                } else {
                    mVvPreviewVideo.start();
                    mIvVideoControl.setSelected(true);
                }
            }
        });
        mLlPreviewClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mVvPreviewVideo.pause();
                if (mOnCloseClickListener != null)
                    mOnCloseClickListener.onCloseClick(mPreviewSelectImageList, position, selectType);
            }
        });
        mLlPreviewSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!selectType.equals(ImageModel.TYPE_ALL) && !selectType.equals(imageModel.getType())) {
                    ToastUtils.showShort(mActivity.getApplicationContext(), "照片和视频不能同时选择");
                    return;
                }


                if (imageModel.getIsChecked()) {
                    if (count > 0) {
                        count -= 1;
                    } else {
                        count = 0;
                    }
                    mTvPreviewSelect.setText("");//被选中的item 取消选中
                } else {
                    if (count + 1 > selectMax) {
                        ToastUtils.showShort(mActivity.getApplicationContext(), selectType.equals(ImageModel.TYPE_VIDEO) ? "最多只能选择" + selectMax + "个视频" : "最多只能选择" + selectMax + "张照片");
                        return;
                    }

                    if (imageModel.getType().equals(ImageModel.TYPE_VIDEO)) {
                        if (imageModel.duration < RevisionMediaActivity.mMinDuration) {
                            ToastUtils.showShort(mActivity.getApplicationContext(), "视频太短啦~最少要够3秒哦~");
                            return;
                        }
                    }

                    count += 1;
                    mTvPreviewSelect.setText(String.valueOf(count));//被选中的item 进行选中
                }
                setPreviewSelectList(imageModel, !imageModel.getIsChecked());
                selectMax = AlbumManageUtils.getSelectMax(selectType, finalNumber);
                //点击之前执行逻辑为相反的逻辑
                mIvPreviewSelect.setVisibility(!imageModel.getIsChecked() ? View.VISIBLE : View.GONE);
                mTvPreviewSelect.setVisibility(imageModel.getIsChecked() ? View.VISIBLE : View.GONE);
                if (onSelectClickListener != null)
                    onSelectClickListener.onSelectListener(mPreviewSelectImageList);
            }
        });
        container.addView(view, 0);

        return view;
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return this.datas.size();
    }

    private void setVideoListener(final VideoView mVvPreviewVideo, final ImageView mIvVideoControl,
                                  final TextView mTvCurrentSpeed, final TextView mTvTotalSpeed, final SeekBar mSbSpeed) {

        mVvPreviewVideo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
                mIvVideoControl.setSelected(true);
            }
        });
        mVvPreviewVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                int duration = mVvPreviewVideo.getDuration();
                mTvTotalSpeed.setText(AlbumManageUtils.stringForTime(duration));
                mSbSpeed.setMax(duration);
                mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                    @Override
                    public void onSeekComplete(MediaPlayer mediaPlayer) {
                        mIvVideoControl.setSelected(true);
                    }
                });
            }
        });
        mVvPreviewVideo.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mIvVideoControl.setSelected(false);
                ToastUtils.showShort(mActivity.getApplicationContext(), "播放出错");
                //异常回调
                return true;//如果方法处理了错误，则为true；否则为false。返回false或根本没有OnErrorListener，将导致调用OnCompletionListener。
            }
        });
        mSbSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                mSlidePro = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //按住进度条停止播放
                mVvPreviewVideo.pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
//手指抬起获取当前SeekBar进度
                mVvPreviewVideo.seekTo(mSlidePro);
            }
        });
        new Thread() {
            @Override
            public void run() {
                try {
                    while (true) {
                        if (mVvPreviewVideo.isPlaying()) {
                            // 如果正在播放，没500.毫秒更新一次进度条
                            mTvCurrentSpeed.post(new Runnable() {
                                @Override
                                public void run() {
                                    int current = mVvPreviewVideo.getCurrentPosition();
                                    mTvCurrentSpeed.setText(AlbumManageUtils.stringForTime(current));
                                    mSbSpeed.setProgress(current);
                                }
                            });
                        }
                        sleep(500);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    /**
     * @param imageModel
     * @param isAddList  true 向集合添加数据
     */
    private void setPreviewSelectList(ImageModel imageModel, boolean isAddList) {


        if (!isAddList) {
            if (mPreviewSelectImageList.contains(imageModel)) {
                imageModel.setIsChecked(false);
                mPreviewSelectImageList.remove(imageModel);
            }
        } else {
            if (!mPreviewSelectImageList.contains(imageModel)) {
                imageModel.setIsChecked(true);
                mPreviewSelectImageList.add(imageModel);
            }
        }
        if (mPreviewSelectImageList.size() <= 0) {
            selectType = ImageModel.TYPE_ALL;
        } else {
            selectType = imageModel.getType();
        }
        if (mOnSelectTypeClickListener != null)
            mOnSelectTypeClickListener.onSelectTypeClick(selectType);
        this.mPreviewSelectImageList = AlbumManageUtils.setSelectSort(mPreviewSelectImageList);
        for (ImageModel model : mPreviewSelectImageList) {
            if (datas.contains(model)) {
                datas.set(datas.indexOf(model), model);
            }
        }

    }
/*

    private void setSelectTypeClick(TextView mTvSelectType, LinearLayout mLlSelectType, LinearLayout mLlPreviewSelect, ImageModel imageModel) {
        if (selectType.equals(ImageModel.TYPE_ALL)) {
            mTvSelectType.setText("");
            mLlSelectType.setVisibility(View.GONE);
            mLlPreviewSelect.setEnabled(true);
        } else if (selectType.equals(ImageModel.TYPE_IMAGE) && imageModel.getType().equals(ImageModel.TYPE_VIDEO)) {
            mTvSelectType.setText("选择图片时不能选择视频");
            mLlSelectType.setVisibility(View.VISIBLE);
            mLlPreviewSelect.setEnabled(false);
        } else if (selectType.equals(ImageModel.TYPE_VIDEO) && imageModel.getType().equals(ImageModel.TYPE_IMAGE)) {
            mTvSelectType.setText("选择视频时不能选择照片");
            mLlPreviewSelect.setEnabled(false);
            mLlSelectType.setVisibility(View.VISIBLE);
        }
    }
*/

    public void setOnCloseClickListener(OnCloseClickListener onCloseClickListener) {
        this.mOnCloseClickListener = onCloseClickListener;
    }

    public void setOnSelectTypeClickListener(OnSelectTypeClickListener onSelectTypeClickListener) {
        this.mOnSelectTypeClickListener = onSelectTypeClickListener;
    }

    public void setOnSelectClickListener(OnSelectClickListener onSelectClickListener) {
        this.onSelectClickListener = onSelectClickListener;
    }


    public interface OnCloseClickListener {
        void onCloseClick(ArrayList<ImageModel> mPreviewSelectImageList, int position, String selectType);
    }

    public interface OnKeyDownClickListener {
        void onKeyDownClick();
    }

    public interface OnSelectTypeClickListener {
        void onSelectTypeClick(String selectType);
    }

    public interface OnSelectClickListener {
        void onSelectListener(ArrayList<ImageModel> mPreviewSelectImageList);
    }


}